//
//  HelloWorldLayer.m
//  isMan
//
//  Created by Xing Lion on 11-6-18.
//  Copyright InspurWorld 2011年. All rights reserved.
//


// Import the interfaces
#import "HelloWorldLayer.h"
#import "BullertSprite.h"
#import "Fly.h"
#import "AppDelegate.h"
#import "GiftSprite.h"
#define MAX_COUNT 40
#define MAX_GIFT 3

#define USE_VELOCITY 1
// HelloWorldLayer implementation
@implementation HelloWorldLayer
@synthesize array = _array;
@synthesize time = _time;
@synthesize fly = _fly;
@synthesize arrayGift = _arrayGift;


- (void) update: (ccTime)delta
{
    // -- keep adding up the playerVelocity to the player's position
    CGPoint pos = _fly.position;
    pos.x += playerVelocity.x;
    pos.y += playerVelocity.y;

    // -- preventing the player sprite from moving outside the screen
    if (pos.x < 10.0)
    {
        pos.x = 10.0;
        playerVelocity = CGPointZero;
    }
    else if (pos.x > 470.0)
    {
        pos.x = 470.0;
        playerVelocity = CGPointZero;
    }
    
    if (pos.y < 10.0) {
        
        pos.y = 10.0;
         playerVelocity = CGPointZero;
    }
    else if(pos.y > 310.0)
    {
    
        pos.y = 310.0;
         playerVelocity = CGPointZero;
    }
    
    
    // assigning the modified position back
    
    [_fly setPosition:pos];
    
}

-(void)realityspeed:(id)sender
{
    _speedfast = NO;
    
    _speedslow = NO;

}

-(void)reality:(id)sender
{

    _fly.invincible = NO;
}

-(void)rightdes:(id)sender
{

    _wrongdes = NO;
}


-(void)changeflyPosition
{

    NSLog(@"changeflyPosition");
    [_fly setPosition:playerVelocity];
}

-(NSUInteger)getlenFrom:(CGPoint)apoint to:(CGPoint)bpoint
{
    

    float lenf =  powf((apoint.x-bpoint.x),2.0)+powf((apoint.y-bpoint.y),2) ;    
    
    int  len = sqrtf(lenf);
    
    return len;
}

-(CGPoint)getPoint:(CGPoint) bpoint rectPoint:(CGPoint)rectpoint
{
    
    CGPoint ptTgt;
    
    float tan = (rectpoint.y - bpoint.y)/(rectpoint.x - bpoint.x);
    
    if (tan < 0) {
        tan = tan*-1.0;
    }
    int deslen ;
    if (1) 
    {
        if (bpoint.x > rectpoint.x && bpoint.y > rectpoint.y) 
        {
            
            // x= 0 y = 0
            deslen = bpoint.y/tan;
            if (deslen > bpoint.x) 
            {
                // x= 0
                
                int ylen = bpoint.x* tan;
                ylen = bpoint.y - ylen;
                
                ptTgt = ccp(0,ylen);
            }
            else
            {
                // y = 0
                
                int xlen = bpoint.y/tan;
                xlen = bpoint.x - xlen;
                
                ptTgt = ccp(xlen,0);
                
            }
        }
        else if(bpoint.x < rectpoint.x && bpoint.y > rectpoint.y)
        {
            // x= 480 y = 0
            deslen = bpoint.y/tan;
            
            if (deslen + bpoint.x > 480) {
                // x = 480
                
                int ylen = (480 - bpoint.x)*tan;
                
                ylen = bpoint.y - ylen;
                
                ptTgt = ccp(480,ylen);
            }
            else
            {
                int xlen = bpoint.y/tan;
                
                xlen = bpoint.x + xlen;
                
                ptTgt = ccp(xlen,0);
                
                // y = 0
            }
            
            
        }
        else if(bpoint.x > rectpoint.x && bpoint.y < rectpoint.y)
        {
            // x = 0 y = 320
            
            deslen = (320 - bpoint.y)/tan;
            
            if (deslen > bpoint.x) 
            {
                // x= 0
                
                int ylen = bpoint.x*tan;
                
                ylen = bpoint.y + ylen;
                
                ptTgt = ccp(0,ylen);
            }
            else
            {
                // y =320
                
                int xlen = (320 - bpoint.y)/tan;
                
                xlen = bpoint.x - xlen;;
                
                ptTgt = ccp(xlen,320);
                
            }
        }
        else
        {
            // x = 480 y = 320
            
            deslen = (320-bpoint.y)/tan;
            
            if ( deslen + bpoint.x > 480)
            {
                int ylen = (480 - bpoint.x)*tan;
                
                ylen = bpoint.y + ylen;
                
                ptTgt = ccp(480,ylen);
                
            }
            else
            {
                int xlen = (320 - bpoint.y)/tan;
                
                xlen = bpoint.x + xlen;
                
                ptTgt = ccp(xlen,320);
            }
        }
        
        
    }
    
    
    return ptTgt;
}


-(CGPoint) randpointFromRect:(CGRect)rect
{
    CGPoint tmpPoint;
    
    int rectlen= rect.size.width;
    int rectwidth = rect.size.height; ;
    
    int x =  arc4random()%(rectlen+1)+ rect.origin.x;
    int y =  arc4random()%(rectwidth+1)+  rect.origin.y;
    
    tmpPoint =ccp(x,y);
    
    
    return tmpPoint;
}

-(void) CallBack:(id)sender
{

    BullertSprite* item = (BullertSprite*)sender;
    id ac1 = [CCHide action];
    
    [item runAction:ac1];
    
    int rand = arc4random()%4;

    
    switch (rand) {
        case 0: 
        {

            int y = arc4random()%321;
            CGPoint point = ccp(0,y);
            
            [item setPosition:point];
            
        }
        break;
            
        case 1:
        {
        
            int y = arc4random()%321;
            CGPoint point = ccp(480,y);
            
            [item setPosition:point];        }
        break;
            
        case 2:
        {
        
            int x = arc4random()%481;
            CGPoint point = ccp(x,0);
            
            [item setPosition:point];
        }
        break;
            
        case 3:
        {
            int x = arc4random()%481;
            CGPoint point = ccp(x,320);
            
            [item setPosition:point];
        }
        break;
        
        default:
            break;
    }
    

    CGRect flyRect = CGRectMake(_fly.position.x, _fly.position.y, 60, 60);
    CGPoint point = [self randpointFromRect:flyRect];
    
    int len = [self getlenFrom:item.position to:point];
    
    CGPoint ptTgt = [self getPoint:item.position rectPoint:point];
    id ac2 = [CCShow action];
    id ac3 ;
    if (_speedfast == YES) {
          ac3 = [CCMoveTo actionWithDuration: len/30 position:ptTgt];
    }
  
    else if (_speedslow == YES) {
          ac3 = [CCMoveTo actionWithDuration: len/10 position:ptTgt];
    }
    
    else 
    {
    
        ac3 = [CCMoveTo actionWithDuration: len/item.speed position:ptTgt];
    }
    
    id acf = [CCCallFuncN actionWithTarget:self selector:@selector(CallBack:)];
    id seq = [CCSequence actions:ac2, ac3,acf, nil];
    [item runAction:seq];

}


-(void)giftCallBack:(id)sender
{

    GiftSprite* sprite=  (GiftSprite*)sender;
    
    [sprite setVisible:NO];

}



-(void)giftAction
{
    
    int giftCount = arc4random()%(MAX_GIFT+1);
    
    giftCount = 1;
    
    
    for(int i = 0 ; i < giftCount ; i++) 
    {

        
        int gifttype = arc4random()%6;

        
        int xpostion = arc4random()%481;
        if (xpostion < 10) {
            xpostion+=15;
        }
        else if(xpostion > 470)
        {
        
            xpostion -= 15;
        }
        
        GiftSprite* sprite = [_arrayGift objectAtIndex:i];
        
        sprite.gifttype = gifttype;
        CGPoint point = ccp(xpostion,320);
        [sprite setPosition:point];
        
        id ac1 = [CCShow action];
        id ac2 = [CCMoveTo actionWithDuration: 5 position:ccp(xpostion,0)];
        
        id acf = [CCCallFuncN actionWithTarget:self selector:@selector(giftCallBack:)];
        id seq = [CCSequence actions:[CCActionInterval actionWithDuration:i*1],ac1, ac2,acf, nil];
        [sprite runAction:seq];
    }
    

}


-(void)bullertAction
{

    for (BullertSprite* item in _array)
    {
        
        
        CGRect frame = CGRectMake(0, 100, 470, 310);
        
        CGPoint tt =[self randpointFromRect:frame];
        [item setPosition:tt];
        CGPoint ptTgt;
        
        CGRect rect = CGRectMake(_fly.position.x, _fly.position.y, 60, 60);
        
        CGPoint point = [self randpointFromRect:rect];
        
        ptTgt =  [self getPoint:tt rectPoint:point];
        

        int len = [self getlenFrom:tt to:point];
        id ac1 = [CCShow action];
        id ac2 = [CCMoveTo actionWithDuration: len/item.speed position:ptTgt];
    
        id acf = [CCCallFuncN actionWithTarget:self selector:@selector(CallBack:)];
        id seq = [CCSequence actions:ac1, ac2,acf, nil];
        [item runAction:seq];
        
    }
    

}

+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	HelloWorldLayer *layer = [HelloWorldLayer node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init])) {
		
        
        _array = [[NSMutableArray alloc] initWithCapacity:20];
        
        _arrayGift = [[NSMutableArray alloc]initWithCapacity:5];

       AppDelegate* dg = (AppDelegate*)[UIApplication sharedApplication].delegate;
        
        int bulletcount ;
        
        switch (dg.leve) {
            case 0:
            {
                bulletcount = 40;
            }
            break;
                
            case 1:
            {
                bulletcount = 60;
            }
            break;
            case 2:
            {
            
                bulletcount = 80;
            }
            break; 
            
            case 3:
            {
                bulletcount = 120;
            }
            break;
            default:
            {
            
                bulletcount = MAX_COUNT;
            }
            break;
        }
        
        for (int i = 0; i<bulletcount; i++) {
            
            
            BullertSprite*   sprite = [BullertSprite BulletWithinLayer:self];
            
            [_array addObject:sprite];
            
            
        }
        
        for (int i = 0; i < MAX_GIFT; i++) {
            
            GiftSprite* spirte = [GiftSprite gitfWithinLayer:self];
            
            [_arrayGift addObject:spirte];
        }
        
        _fly = [Fly FlyWithinLayer:self];
        
        [self bullertAction];
        
        
        CCLabelBMFont *lbScore = [CCLabelBMFont labelWithString:@"Time: 0" fntFile:@"font09.fnt"];
		lbScore.anchorPoint = ccp(1.0, 1.0);
		lbScore.scale = 0.6;
		[self addChild:lbScore z:1 tag:123];
		lbScore.position = ccp(450 , 310);
        
        // change score
		[self schedule:@selector(step:) interval:0.01];
        
        [self schedule:@selector(giftAction) interval:15.0];
        
        
        if (USE_VELOCITY) 
        {
            self.isAccelerometerEnabled = YES;
            [self scheduleUpdate];
        }
    
        
        
        _wrongdes = NO;
        
        _speedfast = NO;
        
        _speedslow = NO;
	}
	return self;
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	
	// don't forget to call "super dealloc"
    
    [_array removeAllObjects];
    [_array release];
    _array = nil;
    
    [_arrayGift removeAllObjects];
    [_arrayGift release];
    _arrayGift = nil;
    
	[super dealloc];
}


-(void) step:(ccTime) dt
{
    _time += 0.01;

	NSString *string = [NSString stringWithFormat:@"Time: %2f", _time];
    NSRange range;
    range.length = 11;
    range.location =0;
    
    NSString* result = [string substringWithRange:range];
	
	CCLabelBMFont *label1 = (CCLabelBMFont*) [self getChildByTag:123];
	[label1 setString:result];
}



-(void) accelerometer:(UIAccelerometer *)accelerometer

        didAccelerate:(UIAcceleration *)acceleration

{
    

    // -- controls how quickly velocity decelerates(lower = quicker to change direction)
    float deceleration = 0.4; 
    // -- determins how sensitive the accelerometer reacts(higher = more sensitive)
    float sensitivity = 6.0;
    // -- how fast the velocity can be at most
    float maxVelocity = 100;
    // adjust velocity based on current accelerometer acceleration
    playerVelocity.x = playerVelocity.x * deceleration - acceleration.y * sensitivity;
    playerVelocity.y = playerVelocity.y * deceleration + acceleration.x * sensitivity;
    // -- we must limit the maximum velocity of the player sprite, in both directions
    if (playerVelocity.x > maxVelocity)
    {
        playerVelocity.x = maxVelocity;
    }
    else if (playerVelocity.x < - maxVelocity)
    {
        playerVelocity.x = - maxVelocity;
    }
    


}

-(void)setGift:(GiftType)type
{

    _gift = type;
    
    switch (type)
    {
        case KChange_big:
        {

            id actionBy = [CCScaleBy actionWithDuration:2  scale: 1.3];

            id actionByBack = [actionBy reverse];
            
            [_fly runAction: [CCSequence actions:actionBy,[CCActionInterval actionWithDuration:5], actionByBack, nil]];
            
       }
        break;
            
        case KChange_small:
        {
        
            id actionBy = [CCScaleBy actionWithDuration:2  scale: 0.7];
            
            id actionByBack = [actionBy reverse];
            
            [_fly runAction: [CCSequence actions:actionBy,[CCActionInterval actionWithDuration:5], actionByBack, nil]];
        }
        break;
            
        case KNo_destory:
        {
            
            _fly.invincible = YES;
            id acf = [CCCallFuncN actionWithTarget:self selector:@selector(reality:)];

            [_fly runAction:[CCSequence actions:[CCActionInterval actionWithDuration:5],acf ,nil]];
        }
        break;
            
        case KWrong_destnation:
        {
        
            _wrongdes = YES;
            id acf = [CCCallFuncN actionWithTarget:self selector:@selector(rightdes:)];
            
            [self runAction:[CCSequence actions:[CCActionInterval actionWithDuration:5],acf ,nil]];
            
        }
        break;
            
        case KSpeed_slow:
        {
            
            _speedslow = YES;
            
            id acf = [CCCallFuncN actionWithTarget:self selector:@selector(realityspeed:)];
            
            [self runAction:[CCSequence actions:[CCActionInterval actionWithDuration:5],acf ,nil]];
        }
        break;    
            
        case KSpeed_Faset:
        {
            _speedfast = YES;
            
            id acf = [CCCallFuncN actionWithTarget:self selector:@selector(realityspeed:)];
            
            [self runAction:[CCSequence actions:[CCActionInterval actionWithDuration:5],acf ,nil]];
        }
        break;
            
        default:
            break;
    }
    
    // do other tings
    
}

@end
